package ventanas;

import beans.Usuario;
import db.Model;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class InicioSesion extends javax.swing.JFrame {

    Model m;

    public InicioSesion() {

        m = Model.getInstance();
        this.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/img/icono.png")).getImage());
        
       
        initComponents();
        setTitle("Iniciar Sesión");
        setSize(Toolkit.getDefaultToolkit().getScreenSize());

        //posicionando objetos
        logo.setBounds(this.getWidth() / 4 - (logo.getWidth() / 2), this.getHeight() / 2 - (logo.getHeight() / 2), logo.getWidth(), logo.getHeight());
        panelin.setBounds((this.getWidth() / 4 * 3) - (panelin.getWidth() / 2), (this.getHeight() / 2) - (panelin.getHeight() / 2), panelin.getWidth(), panelin.getHeight());
        fondoinicio.setBounds((this.getWidth() / 4 * 3) - (fondoinicio.getWidth() / 2) + 20, (this.getHeight() / 2) - (fondoinicio.getHeight() / 2) - 20, fondoinicio.getWidth(), fondoinicio.getHeight());
        separador.setBounds(this.getWidth() / 2, this.getHeight() / 2 - (separador.getHeight() / 2) - 15, separador.getWidth(), separador.getHeight());
        linea.setBounds(0, 0, this.getWidth(), linea.getHeight());


        iniciar();
    }

    public void setVisible(boolean sw){
        super.setVisible(sw);
        iniciar();
    }

    public void iniciar() {
        usuario.removeAllItems();
        try {
            List<Usuario> listaUsuarios = (List<Usuario>) m.obtenerListado("obtenerUsuarios");

            for (Usuario obj : listaUsuarios) {
                usuario.addItem(obj.getUsuario());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        clave.requestFocus();
    }

    public void onIniciarSesion() {
        if (clave.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Digite Contraseña para poder iniciar sesión", "Información", JOptionPane.INFORMATION_MESSAGE);
            clave.requestFocus();
        } else {
            try {
                Usuario user = (Usuario) m.obtenerRegistro("obtenerUsuario", new Usuario("" + usuario.getSelectedItem(), clave.getText()));

                if (user != null) {
                    m.setUsuario(user);
                    new Principal(this);
                    this.dispose();
                    this.clave.setText("");
                } else {
                    JOptionPane.showMessageDialog(this, "Contraseña Incorrecta", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panel = new javax.swing.JPanel();
        logo = new javax.swing.JLabel();
        panelin = new javax.swing.JPanel();
        salir = new javax.swing.JButton();
        entrar = new javax.swing.JButton();
        clave = new javax.swing.JPasswordField();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        usuario = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        fondoinicio = new javax.swing.JLabel();
        separador = new javax.swing.JSeparator();
        linea = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.CardLayout());

        panel.setBackground(new java.awt.Color(255, 255, 255));
        panel.setLayout(null);

        logo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/logogrande.png"))); // NOI18N
        panel.add(logo);
        logo.setBounds(50, 180, 335, 248);

        panelin.setBackground(new java.awt.Color(255, 255, 255));
        panelin.setLayout(null);

        salir.setBackground(new java.awt.Color(0, 153, 255));
        salir.setFont(new java.awt.Font("Tahoma", 1, 11));
        salir.setForeground(new java.awt.Color(0, 51, 153));
        salir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cerrar.png"))); // NOI18N
        salir.setText("Salir");
        salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salirActionPerformed(evt);
            }
        });
        panelin.add(salir);
        salir.setBounds(140, 100, 90, 23);

        entrar.setBackground(new java.awt.Color(0, 153, 255));
        entrar.setFont(new java.awt.Font("Tahoma", 1, 11));
        entrar.setForeground(new java.awt.Color(0, 51, 153));
        entrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/ok.png"))); // NOI18N
        entrar.setText("Entrar");
        entrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                entrarActionPerformed(evt);
            }
        });
        panelin.add(entrar);
        entrar.setBounds(40, 100, 90, 23);

        clave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                claveActionPerformed(evt);
            }
        });
        panelin.add(clave);
        clave.setBounds(70, 70, 160, 20);

        jLabel2.setForeground(new java.awt.Color(51, 153, 255));
        jLabel2.setText("Contraseña");
        panelin.add(jLabel2);
        jLabel2.setBounds(10, 70, 56, 14);

        jLabel1.setForeground(new java.awt.Color(51, 153, 255));
        jLabel1.setText("Usuario");
        panelin.add(jLabel1);
        jLabel1.setBounds(10, 40, 36, 14);

        usuario.setBackground(new java.awt.Color(0, 153, 255));
        usuario.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        panelin.add(usuario);
        usuario.setBounds(70, 40, 160, 20);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel3.setForeground(new java.awt.Color(51, 153, 255));
        jLabel3.setText("Por favor digite su Usuario y Contraseña");
        panelin.add(jLabel3);
        jLabel3.setBounds(10, 0, 260, 14);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel5.setForeground(new java.awt.Color(51, 153, 255));
        jLabel5.setText("para  ingresar al sistema");
        panelin.add(jLabel5);
        jLabel5.setBounds(50, 10, 160, 20);

        panel.add(panelin);
        panelin.setBounds(620, 140, 240, 130);

        fondoinicio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/inicio.png"))); // NOI18N
        panel.add(fondoinicio);
        fondoinicio.setBounds(590, 70, 350, 230);

        separador.setBackground(new java.awt.Color(153, 204, 255));
        separador.setOrientation(javax.swing.SwingConstants.VERTICAL);
        panel.add(separador);
        separador.setBounds(490, 20, 10, 490);

        linea.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/linea.png"))); // NOI18N
        linea.setText("jLabel4");
        panel.add(linea);
        linea.setBounds(0, 0, 960, 130);

        getContentPane().add(panel, "card2");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void salirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salirActionPerformed
        // TODO add your handling code here:
        System.exit(0);
}//GEN-LAST:event_salirActionPerformed

    private void entrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_entrarActionPerformed
        onIniciarSesion();
}//GEN-LAST:event_entrarActionPerformed

    private void claveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_claveActionPerformed
        onIniciarSesion();
    }//GEN-LAST:event_claveActionPerformed

    public void paint(Graphics g) {
        super.paint(g);
        panelin.getGraphics().drawImage(new ImageIcon("img/inicio.png").getImage(), 0, 0, this);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws UnsupportedLookAndFeelException {
        try {
            // Set cross-platform Java L&F (also called "Metal")
            UIManager.setLookAndFeel(
                    UIManager.getSystemLookAndFeelClassName());
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new InicioSesion().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPasswordField clave;
    private javax.swing.JButton entrar;
    private javax.swing.JLabel fondoinicio;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel linea;
    private javax.swing.JLabel logo;
    private javax.swing.JPanel panel;
    private javax.swing.JPanel panelin;
    private javax.swing.JButton salir;
    private javax.swing.JSeparator separador;
    private javax.swing.JComboBox usuario;
    // End of variables declaration//GEN-END:variables
}